/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.user

import org.ibiblio.terasaur.user.OpenId
import org.ibiblio.terasaur.item.Item
import org.ibiblio.terasaur.bt.Seedbank
import org.ibiblio.terasaur.item.Collection
import org.joda.time.DateTime
import org.joda.time.contrib.hibernate.PersistentDateTime

class User {
    transient springSecurityService

    Long id
    String username
    String password
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    List openIds
    Set items
    Set collections
    // autoTimestamp attributes
    DateTime dateCreated
    DateTime lastUpdated

    static hasMany = [openIds: OpenId, items: Item, seedbanks: Seedbank, collections: Collection]

    static constraints = {
        username blank: false, unique: true, minSize: 5, maxSize: 15, matches: '[a-zA-Z][a-zA-Z0-9_-]+'
        password blank: false
        openIds(nullable: true)
        items(nullable: true)
    }

    static mapping = {
        table 'ts_user'
        id type: 'long', generator: 'native'
        password column: '`password`'
        autoTimestamp true
        items lazy: true
        seedbanks lazy: true
        collections lazy: true
        dateCreated type: PersistentDateTime
        lastUpdated type: PersistentDateTime
    }

    Set<Role> getAuthorities() {
        UserRole.findAllByUser(this).collect { it.role } as Set
    }

    def beforeInsert() {
        if (password) {
            encodePassword()
        }
    }

    def beforeUpdate() {
        if (password && isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}
